package dao

import (
	dom "a-common/domain"
	"a-demo/domain/entity"
	"strings"
	"sync"
)

var (
	senMomDaoTemp *SenMomDao
	senMomDaoOnce sync.Once
)

type SenMomDao struct{}

func NewSenMomDao() *SenMomDao {
	senMomDaoOnce.Do(func() {
		senMomDaoTemp = &SenMomDao{}
	})
	return senMomDaoTemp
}

// List 分页
func (m *SenMomDao) List(args *entity.SenMomDto, isExprot bool) (dom.PageVo, error) {
	// 构建查询条件
	query := pgCli.Table(&entity.SenMom{}).Where("1 = 1")
	if args.MomCode != "" {
		query.And("mom_no = ?", args.MomCode)
	}
	if args.MomName != "" {
		query.And("mom_name = ?", args.MomName)
	}
	if args.Status != "" {
		query.And("status = ?", args.Status)
	}
	if args.PageSize != 0 {
		query.Limit(args.PageSize, (args.PageNum-1)*args.PageSize)
	}

	// 查询
	var vPage dom.PageVo
	if isExprot {
		var rows []entity.SenMomExportVo
		total, err := query.Asc("mom_id").FindAndCount(&rows)
		if err != nil {
			return vPage, err
		}
		vPage.Rows = rows
		vPage.Total = total
	} else {
		var rows []entity.SenMomPageVo
		total, err := query.Asc("mom_id").FindAndCount(&rows)
		if err != nil {
			return vPage, err
		}
		vPage.Rows = rows
		vPage.Total = total
	}
	vPage.PageNum = args.PageNum
	vPage.PageSize = args.PageSize
	return vPage, nil
}

// Del 删
func (m *SenMomDao) Del(ids string) (int64, error) {
	return pgCli.In("mom_id", strings.Split(ids, `,`)).Delete(&entity.SenMom{})
}

// Get 查
func (m *SenMomDao) Get(id string) (entity.SenMomVo, error) {
	var v entity.SenMomVo
	_, err := pgCli.Table(&entity.SenMom{}).ID(id).Get(&v)
	return v, err
}

// Add 增
func (m *SenMomDao) Add(args *entity.SenMomDto) (int64, error) {
	return pgCli.InsertOne(&entity.SenMom{
		MomCode: args.MomCode,
		MomName: args.MomName,
		MomSort: args.MomSort,
		Status:  args.Status,
		BaseStruct: dom.BaseStruct{
			CreatedBy: args.CreatedBy,
			UpdatedBy: args.CreatedBy,
			Remark:    args.Remark,
		},
	})
}

// Edit 改
func (m *SenMomDao) Edit(args *entity.SenMomDto) (int64, error) {
	return pgCli.ID(args.MomId).Update(&entity.SenMom{
		MomCode: args.MomCode,
		MomName: args.MomName,
		MomSort: args.MomSort,
		Status:  args.Status,
		BaseStruct: dom.BaseStruct{
			UpdatedBy: args.UpdatedBy,
			Remark:    args.Remark,
		},
	})
}
